package iosr11.ui.data;

import iosr11.Service.ServiceLocatorImpl;
import iosr11.Service.EventService;
import iosr11.data.Event;
import iosr11.data.Student;
import iosr11.ui.common.CurrentUserBean;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.faces.component.html.HtmlDataTable;
import javax.faces.context.FacesContext;


public class EventListBean {
	private Logger logger = Logger.getLogger("iosr.ui.data");
    private List<Event> eventList;
	private EventService service;
	private HtmlDataTable dataTable;
	private CurrentUserBean currentUser; 
    
	public EventListBean() {
		this.service = (EventService)ServiceLocatorImpl.getInstance().getService(Event.class);
		//this.ensureListNotNull();
		if(this.service==null){
			logger.severe("Could not obtain reference to EventService");
			return;
		}
	}
	
	public List<Event> getEvents(){
		if(this.service != null){
			Student student = currentUser.getStudent();
			if(student != null)
				this.eventList = service.getStudentEvents(student);
			else
				this.eventList = service.getAllEvents();
		}
		if(this.eventList == null){
			this.eventList = new ArrayList<Event>();
		}
		return this.eventList;
	}
	
	public HtmlDataTable getDataTable(){
		return this.dataTable;
	}
	public void setDataTable(HtmlDataTable table){
		this.dataTable = table;
	}
	
	private void saveSelectedEventId(){
		 Event selectedEvent = (Event) dataTable.getRowData();
		 FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put(
				 SessionMapKeys.SelectedEventID.name(), selectedEvent.getId());
	}
	
	public String goToEventDetails(){
		 saveSelectedEventId();
		 return "showEvent";
	} 
	public String editEventDetails(){
		 saveSelectedEventId();
		 return "editEvent";
	} 

	public String addEventDetails(){
		 FacesContext.getCurrentInstance().getExternalContext().getSessionMap().remove(SessionMapKeys.SelectedEventID.name());
		 return "editEvent";
	} 
	
	public CurrentUserBean getCurrentUser() {
		return currentUser;
	}
	
	public void setCurrentUser(CurrentUserBean currentUser) {
		this.currentUser = currentUser;
	}
}


